package org.dromara.cms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.cms.domain.bo.CmsCategoryBo;
import org.dromara.cms.domain.vo.CmsCategoryVo;
import org.dromara.cms.service.ICmsCategoryService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

import static cn.dev33.satoken.SaManager.log;

/**
 * CMS分类
 *
 * @author Spring
 * @date 2024-12-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/cms/category")
public class CmsCategoryController extends BaseController {

    private final ICmsCategoryService cmsCategoryService;

    private final ResourceLoader resourceLoader;

    /**
     * 查询模板列表
     */
    @SaCheckPermission("cms:category:list")
    @GetMapping("/getTemplatesList")
    public R<List<String>> getTemplatesList() {
        try {
            List<String> templates = new ArrayList<>();
            
            // 使用 PathMatchingResourcePatternResolver 来查找模板文件
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath:templates/**/*.html");
            
            for (Resource resource : resources) {
                String path = resource.getURL().getPath();
                // 获取相对路径
                String template = path.substring(path.indexOf("templates/"));
                // 排除包含 base 的模板
                if (!template.contains("base")) {
                    // 确保使用正斜杠，移除开头的 templates/
                    template = StringUtils.replace(template.substring("templates/".length()), "\\", "/");
                    templates.add(template);
                }
            }
            
            return R.ok(templates);
        } catch (IOException e) {
            log.error("获取模板列表失败", e);
            return R.fail("获取模板列表失败");
        }
    }

    /**
     * 查询CMS分类列表
     */
    @SaCheckPermission("cms:category:list")
    @GetMapping("/list")
    public TableDataInfo<CmsCategoryVo> list(CmsCategoryBo bo, PageQuery pageQuery) {
        return cmsCategoryService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出CMS分类列表
     */
    @SaCheckPermission("cms:category:export")
    @Log(title = "CMS分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CmsCategoryBo bo, HttpServletResponse response) {
        List<CmsCategoryVo> list = cmsCategoryService.queryList(bo);
        ExcelUtil.exportExcel(list, "CMS分类", CmsCategoryVo.class, response);
    }

    /**
     * 获取CMS分类详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("cms:category:query")
    @GetMapping("/{id}")
    public R<CmsCategoryVo> getInfo(@NotNull(message = "主键不能为空")
                                    @PathVariable Long id) {
        return R.ok(cmsCategoryService.queryById(id));
    }

    /**
     * 新增CMS分类
     */
    @SaCheckPermission("cms:category:add")
    @Log(title = "CMS分类", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CmsCategoryBo bo) {
        return toAjax(cmsCategoryService.insertByBo(bo));
    }

    /**
     * 修改CMS分类
     */
    @SaCheckPermission("cms:category:edit")
    @Log(title = "CMS分类", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CmsCategoryBo bo) {
        return toAjax(cmsCategoryService.updateByBo(bo));
    }

    /**
     * 删除CMS分类
     *
     * @param ids 主键串
     */
    @SaCheckPermission("cms:category:remove")
    @Log(title = "CMS分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(cmsCategoryService.deleteWithValidByIds(List.of(ids), true));
    }
}
